import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yishop/config/Config.dart';
import 'package:flutter_yishop/config/EventBus.dart';
import 'package:flutter_yishop/constants/Constants.dart';
import 'package:flutter_yishop/services/SignService.dart';
import 'package:flutter_yishop/services/UserService.dart';
import 'package:flutter_yishop/utils/screen/ScreenAdapter.dart';
import 'package:flutter_yishop/utils/toast_util.dart';
import 'package:flutter_yishop/widget/DialogWidget.dart';

class AddressList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _AddressListState();
  }
}

class _AddressListState extends State<AddressList> {

  List addressList= [];


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this._getAddressList();
    if(mounted){
      eventBus.on<AddressEvent>().listen((event) {
        this._getAddressList();
      });
    }

  }

  //获取收货地址
  _getAddressList() async {

    List userinfo = UserService.getUserInfo();
    var tempJson ={
      "uid": userinfo[0]["_id"],
      "salt": userinfo[0]["salt"]
    };

    var sign = SignService.getSign(tempJson);
    var api = "${Config.url}api/addressList?uid=${userinfo[0]["_id"]}&sign=$sign";
    var response = await Dio().get(api);
    if(response.data["success"]){
      if(mounted){
        setState(() {
          this.addressList = response.data["result"];
        });
      }

    }

  }


  //修改默认收货地址
  _changeDefaultAddress(id) async{

    List userinfo = await UserService.getUserInfo();

    var tempJson = {"uid": userinfo[0]['_id'], "id":id,"salt": userinfo[0]["salt"]};

    var sign = SignService.getSign(tempJson);

    var api =
        '${Config.url}api/changeDefaultAddress';
    var response = await Dio().post(api,data:{
      "uid": userinfo[0]['_id'],
      "id":id,
      "sign":sign
    });
    if(response.data["success"]){
      if(mounted)
      Navigator.pop(context);
    }else{
      ToastUtil.showToasts(response.data["message"]);
    }


  }

  //删除收货地址

  _delAddress(id) async{

    List userinfo=await UserService.getUserInfo();
    var tempJson={
      "uid":userinfo[0]["_id"],
      "id":id,
      "salt":userinfo[0]["salt"]
    };

    var sign=SignService.getSign(tempJson);

    var api = '${Config.url}api/deleteAddress';
    var response = await Dio().post(api,data:{
      "uid":userinfo[0]["_id"],
      "id":id,
      "sign":sign
    });
    if(response.data["success"]){
      this._getAddressList();   //删除收货地址完成后重新获取列表
    }else{
      ToastUtil.showToasts(response.data["message"]);
    }
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenAdapter.init(context);
    return Scaffold(
        appBar: AppBar(
          title: Text("收货地址列表"),
        ),
        body: Container(
          child: Stack(
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(bottom: ScreenAdapter.height(88)),
                child: this.addressList.length>0?
                ListView.builder(
                    itemCount: addressList.length,
                    itemBuilder: (context,index){
                      return _addressItem(addressList,index);
                    })
                    :Center(
                  child: Text("暂无收货地址"),
                ),
              ),

              Positioned(
                bottom: 0,
                width: ScreenAdapter.width(750),
                height: ScreenAdapter.height(88),
                child: Container(
                  padding: EdgeInsets.all(5),
                  width: ScreenAdapter.width(750),
                  height: ScreenAdapter.height(88),
                  decoration: BoxDecoration(
                      color: Colors.red,
                      border: Border(
                          top: BorderSide(width: 1, color: Colors.red))),
                  child: InkWell(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.add, color: Colors.white),
                        Text("增加收货地址", style: TextStyle(color: Colors.white))
                      ],
                    ),
                    onTap: (){
                      Navigator.pushNamed(context,Constants.ADDRESSADD);
                    },
                  ),
                ),
              )
            ],
          ),
        ));
  }

  Widget _addressItem(addressList,index){
    String allAddress =addressList[index]["address"];
    String province = "";//省
    String city="";//市
    String county="";//区
    String detailsAddress = "";//详细地址
    try{
      province = allAddress.substring(allAddress.indexOf("p:")+2,allAddress.indexOf("c:"));
      city = allAddress.substring(allAddress.indexOf("c:")+2,allAddress.indexOf("t:"));
      county = allAddress.substring(allAddress.indexOf("t:")+2,allAddress.indexOf("a:"));
      detailsAddress = allAddress.substring(allAddress.indexOf("a:")+2,allAddress.length);
    }catch(e){

    }

    return Container(
      padding: EdgeInsets.only(top:ScreenAdapter.width(15)),
      child:  Column(
        children: [
          ListTile(
            leading:  addressList[index]["default_address"]==1?Icon(Icons.check, color: Colors.red):null,
            title: GestureDetector(
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Row(
                      children: [
                        Text("${addressList[index]["name"]}",style: TextStyle(
                            fontSize: 18,fontWeight: FontWeight.bold
                        ),),
                        Container(
                          margin: EdgeInsets.only(left: ScreenAdapter.width(20)),
                          child:  Text("${addressList[index]["phone"]}",style: TextStyle(
                              fontSize: 15
                          ),),
                        )
                      ],
                    ),
                    SizedBox(height: 10),
                    Text("$province$city$county $detailsAddress",style: TextStyle(
                        color: Colors.black45,
                        fontSize: 14
                    ),),
                  ]),
              onTap: (){
                this._changeDefaultAddress(addressList[index]["_id"]);
              },
              onLongPress: (){
                DialogWidget.showAlertDialog(context,
                    confirmOnTap: (){
                      _delAddress(addressList[index]["_id"]);
                });
              },
            ),
            trailing: IconButton(icon: Icon(Icons.edit, color: Colors.blue),
            onPressed: (){
              Navigator.pushNamed(context, Constants.ADDRESSEDIT,
                  arguments: {
                    "id":this.addressList[index]["_id"],
                    "name":this.addressList[index]["name"],
                    "phone":this.addressList[index]["phone"],
                    "address":this.addressList[index]["address"],
                  });
            },),
          ),
          Divider(),
        ],
      ),
    );
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    eventBus.fire(new CheckoutEvent("修改成功"));
  }
}
